package com.lingying.caiwudailikehudaun.utils.DaoRuUtils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class BaoBiaoExcelUtil {

//    private final static Logger log = LoggerFactory.getLogger(BaoBiaoExcelUtil.class);

    private final static String EXCEL2003 = "xls";
    private final static String EXCEL2007 = "xlsx";


    /**
     * 解析excel表格
     * 注：要先用@ExcelColumn注解在你指定的bean中标明该属性要存储的哪一行的数据表头是什么
     * 例： 我想将解析后的数据存到FuZhaiBiaoBean里保存
     * FuZhaiBiaoBean：
     *
     * @param <T>
     * @param path 存储前端文件的路径，但未被使用可以传一个空字符串
     * @param cls  bean类的class属性，如 KeHuBean.class
     * @param file 从前端传到后端的Excel文件
     * @return
     * @ExcelColumn(value = "资产",col = 0)
     * private String kuaiJiKeMu; // 会计科目
     * @ExcelColumn(value = "行次",col = 1)
     * private String hangCi; // 行次
     * @ExcelColumn(value = "期末余额",col = 2)
     * private Integer qiChuJinE; // 期初金额
     * @ExcelColumn(value = "年初余额",col = 3)
     * private Integer qiMoJinE; // 期末金额
     * 调用代码：
     * List<FuZhaiBiaoBean> fuZhaiBiaoBeanList = ExcelUtil.readExcel("", FuZhaiBiaoBean.class, file);
     */
    public static <T> List<T> readExcel(String path, Class<T> cls, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
//            log.error("上传文件格式不正确");
        }
        List<T> dataList = new ArrayList<>();
        Workbook workbook = null;
        try {
            InputStream is = file.getInputStream();
            if (fileName.endsWith(EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.endsWith(EXCEL2003)) {
                workbook = new HSSFWorkbook(is);
            }
            if (workbook != null) {
                //类映射  注解 value-->bean columns
                Map<String, List<Field>> classMap = new HashMap<>();
                Map<Integer, List<Integer>> needCol = new HashMap<>();
                List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
                fields.forEach(
                        field -> {
                            ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                            if (annotation != null) {
                                String value = annotation.value();
                                if (StringUtils.isBlank(value)) {
                                    return;//return起到的作用和continue是相同的 语法
                                }
                                if (!needCol.containsKey(annotation.row())) {
                                    needCol.put(annotation.row(), new ArrayList<>());
                                }
                                if (!classMap.containsKey(annotation.col() + "_" + annotation.row())) {
                                    classMap.put(annotation.col() + "_" + annotation.row(), new ArrayList<>());
                                }
                                field.setAccessible(true);
                                needCol.get(annotation.row()).add(annotation.col());
                                classMap.get(annotation.col() + "_" + annotation.row()).add(field);
                            }
                        }
                );
                //获取第一个工作表中的合并单元格并存入CellRange数组
                Sheet sheet = workbook.getSheetAt(0);
                try {
                    T t = cls.newInstance();
                    int rownum = sheet.getPhysicalNumberOfRows(); //行数
                    //判断是否为空白行
                    needCol.keySet().forEach(startrow -> {
                        int count = dataList.size();
                        for (int i = startrow; i < rownum; i++) {
                            Row row = sheet.getRow(i);
                            if (row != null) {
                                needCol.get(startrow).forEach(colnum -> {
                                    if (classMap.containsKey(colnum + "_" + startrow)) {
                                        String cellData = getCellValue(row.getCell(colnum));
                                        if (cellData.equals("")) {
                                            cellData = "0";
                                        }
                                        List<Field> fieldList = classMap.get(colnum + "_" + startrow);
                                        String finalCellData = cellData;
                                        fieldList.forEach(x -> {
                                            try {
                                                handleField(t, finalCellData, x);
                                            } catch (Exception e) {
//                                                log.error(String.format("reflect field:%s value:%s exception!", x.getName(), finalCellData), e);
                                            }
                                        });
                                        dataList.add(t);
                                    }
                                });
                                if (count<dataList.size()){
                                    break;
                                }
                            } else {
                                break;
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
//            log.error(String.format("parse excel exception!"), e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
//                    log.error(String.format("parse excel exception!"), e);
                }
            }
        }
        return dataList;
    }

    /**
     * @Description: 判断单元格是否是合并单元格
     * @Author: fw
     * @Date: 2019/12/27 15:09
     */
    public static Result isMergeCell(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    //excel物理行数和我们的逻辑行数不同，所以需要加1显示
                    return new Result(true, firstRow + 1, lastRow + 1, firstColumn + 1, lastColumn + 1);
                }
                ;
            }
        }
        ;
        return new Result(false, row, row, column, column);

    }

    /**
     * 向bean中添加数据
     * 注：该方法为工具类内部调用
     * 用于存储金额，如当为小数时乘100在进行存储
     *
     * @param t     bean类
     * @param value 表格中的值
     * @param field
     * @param <T>
     * @throws Exception
     */
    private static <T> void handleField(T t, String value, Field field) throws Exception {

        Class<?> type = field.getType();
        if (type == null || type == void.class || StringUtils.isBlank(value)) {
            return;
        }
        System.out.println("type------------------------->" + type);
        System.out.println("value------------------------->" + value);
        if (type == Object.class) {
            field.set(t, value);
            //数字类型
        } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
            if (type == int.class || type == Integer.class) {
                value = keepTwoBit(value);
                String str = Integer.toString((int) (Double.parseDouble(value) * 100));
                System.out.println("str----------------------->" + str);
                field.set(t, NumberUtils.toInt(str));
            } else if (type == long.class || type == Long.class) {
                field.set(t, NumberUtils.toLong(value));
            } else if (type == byte.class || type == Byte.class) {
                field.set(t, NumberUtils.toByte(value));
            } else if (type == short.class || type == Short.class) {
                field.set(t, NumberUtils.toShort(value));
            } else if (type == double.class || type == Double.class) {
                value = keepTwoBit(value);
                String str = Integer.toString((int) (Double.parseDouble(value) * 100));
                field.set(t, NumberUtils.toInt(str));
            } else if (type == float.class || type == Float.class) {
                field.set(t, NumberUtils.toFloat(value));
            } else if (type == char.class || type == Character.class) {
                field.set(t, CharUtils.toChar(value));
            } else if (type == boolean.class) {
                field.set(t, BooleanUtils.toBoolean(value));
            } else if (type == BigDecimal.class) {
                field.set(t, new BigDecimal(value));
            }
        } else if (type == Boolean.class) {
            field.set(t, BooleanUtils.toBoolean(value));
        } else if (type == Date.class) {
            field.set(t, value);
        } else if (type == String.class) {
            field.set(t, value);
        } else {
            Constructor<?> constructor = type.getConstructor(String.class);
            field.set(t, constructor.newInstance(value));
        }
    }

    /**
     * 不用科学计数法来显示小数
     *
     * @param zxje
     * @return
     */
    public static String keepTwoBit(String zxje) {
        try {
            BigDecimal bd = new BigDecimal(zxje);
            double zxjeF = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            DecimalFormat df = new DecimalFormat("#.00");
            zxje = df.format(zxjeF) + "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return zxje;
    }

    /**
     * 得到表格中单元格的值
     *
     * @param cell
     * @return
     */
    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

    /**
     * 写入excel文件接口
     *
     * @param response
     * @param dataList
     * @param cls
     * @param fileName
     * @param <T>
     */
    public static <T> void writeExcel(HttpServletResponse response, List<T> dataList, Class<T> cls, String
            fileName) {
        Field[] fields = cls.getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields)
                .filter(field -> {
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null && annotation.col() > 0) {
                        field.setAccessible(true);
                        return true;
                    }
                    return false;
                }).sorted(Comparator.comparing(field -> {
                    int col = 0;
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null) {
                        col = annotation.col();
                    }
                    return col;
                })).collect(Collectors.toList());

        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");
        AtomicInteger ai = new AtomicInteger();
        {
            Row row = sheet.createRow(ai.getAndIncrement());
            AtomicInteger aj = new AtomicInteger();
            //写入头部
            fieldList.forEach(field -> {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                String columnName = "";
                if (annotation != null) {
                    columnName = annotation.value();
                }
                Cell cell = row.createCell(aj.getAndIncrement());
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                Font font = wb.createFont();
                cellStyle.setFont(font);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(columnName);
            });
        }
        if (CollectionUtils.isNotEmpty(dataList)) {
            dataList.forEach(t -> {
                Row row1 = sheet.createRow(ai.getAndIncrement());
                AtomicInteger aj = new AtomicInteger();
                fieldList.forEach(field -> {
                    Class<?> type = field.getType();
                    Object value = "";
                    try {
                        value = field.get(t);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Cell cell = row1.createCell(aj.getAndIncrement());
                    if (value != null) {
                        if (type == Date.class) {
                            cell.setCellValue(value.toString());
                        } else {
                            cell.setCellValue(value.toString());
                        }
                        cell.setCellValue(value.toString());
                    }
                });
            });
        }
        //冻结窗格
        wb.getSheet("Sheet1").createFreezePane(0, 1, 0, 1);
        //浏览器下载excel
        buildExcelDocument(fileName, wb, response);
    }

    /**
     * 浏览器下载excel
     *
     * @param fileName
     * @param wb
     * @param response
     */
    private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成excel文件
     *
     * @param path 生成excel路径
     * @param wb
     */
    private static void buildExcelFile(String path, Workbook wb) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            wb.write(new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}